//-----------------------------------------------------------------------------
// Bend2D - Physics Engine
// Roberto Bender <beto.bender@gmail.com>
// Description: 
// Date: 08/03/2010
//-----------------------------------------------------------------------------
#include "benchmarking.h"
#include "log.h"
#ifdef LINUX
#include <unistd.h>
#endif
using namespace bend2d;

StopWatch::StopWatch()
{
#ifdef LINUX
    m_Running = false;
#elif WIN32
    m_Running = false;
#endif
}

void StopWatch::Start()
{
#ifdef LINUX
    gettimeofday(&m_Start, NULL);
    m_Running = true;
#elif WIN32
    GetSystemTime(&m_Start);
    m_Running = true;
#endif
}

void StopWatch::Stop()
{
#ifdef LINUX
    gettimeofday(&m_End, NULL);
    m_Running = false;
#elif WIN32
    GetSystemTime(&m_End);
    m_Running = false;
#endif
}

void StopWatch::Reset()
{
#ifdef LINUX
    if(m_Running)
        gettimeofday(&m_Start, NULL);
#elif WIN32
    if(m_Running)
        GetSystemTime(&m_Start);
#endif
}

unsigned int StopWatch::GetTime() const
{
#ifdef LINUX
    struct timeval end = m_End;
    if(m_Running)
        gettimeofday(&end, NULL);

    long seconds  = end.tv_sec  - m_Start.tv_sec;
    long useconds = end.tv_usec - m_Start.tv_usec;

    return ((seconds) * 1000 + useconds/1000.0) + 0.5;
#elif WIN32
    SYSTEMTIME end;
    if(m_Running)
        GetSystemTime(&end);
    
    FILETIME startft, endft;
    SystemTimeToFileTime(&m_Start, &startft);
    SystemTimeToFileTime(&end, &endft);

    ULARGE_INTEGER uli1;
    uli1.LowPart = startft.dwLowDateTime; // could use memcpy here!
    uli1.HighPart = startft.dwHighDateTime;

    ULARGE_INTEGER uli2;
    uli2.LowPart = endft.dwLowDateTime; // could use memcpy here!
    uli2.HighPart = endft.dwHighDateTime;

    ULONGLONG systemTimeIn_ms_start( uli1.QuadPart/10000 );
    ULONGLONG systemTimeIn_ms_end( uli2.QuadPart/10000 );

    return (int) (systemTimeIn_ms_end - systemTimeIn_ms_start);
#else
     return 0;
#endif
}





